<template>
  <div class="app-container">
    <div class="search-container" style="padding-bottom: 18px; display: flex">
      <el-button type="primary" style="margin-left: 10px" @click="createMenu"
        >添加角色</el-button
      >
    </div>

    <el-card shadow="never" class="table-container">
      <el-table
        :data="tableData"
        row-key="id"
        style="width: 100%"
        default-expand-all
      >
        <el-table-column prop="id" label="编号" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="description" label="描述" />
        <el-table-column sortable prop="createTime" label="添加时间">
          <template #default="scope">
            {{ formatDateTime(new Date(scope.row.createTime)) }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click="allocateMenu(scope.row)"
            >
              分配菜单
            </el-button>
            <el-button
              link
              type="primary"
              size="small"
              @click="handleUpdate(scope.row)"
            >
              更新
            </el-button>
            <el-button
              link
              type="primary"
              size="small"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog v-model="updateDialogFormVisible" title="更新角色" width="800">
      <el-form
        :model="form"
        label-width="auto"
        style="max-width: 400px; margin-top: 20px"
      >
        <el-form-item label="ID" style="width: 240px">
          <el-input disabled v-model="curRow.id" />
        </el-form-item>
        <el-form-item label="名称" style="width: 240px">
          <el-input v-model="curRow.name" />
        </el-form-item>
        <el-form-item label="描述" style="width: 240px">
          <el-input v-model="curRow.description" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="updateDialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmUpdate"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="createDialogFormVisible" title="添加菜单" width="800">
      <el-form
        :model="form"
        label-width="auto"
        style="max-width: 400px; margin-top: 20px"
      >
        <el-form-item label="名称">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="createDialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCreate"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="allocateDialogFormVisible" title="分配菜单" width="800">
      <el-form
        :model="form"
        label-width="auto"
        style="max-width: 400px; margin-top: 20px"
      >
        <el-form-item label="菜单">
          <el-cascader
            v-model="allocForm.menuIds"
            :options="menuList"
            :props="{ multiple: true }"
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="allocateDialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAllocate"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import RoleAPI from "@/api/role";
import MenuAPI from "@/api/menu";
import { ElMessage } from "element-plus";
import { tr } from "element-plus/es/locale";

const params: any = ref({
  keyword: "",
  pageSize: 5,
  pageNum: 1,
});

const form: any = reactive({
  name: "",
  description: "",
});

const allocForm: any = reactive({
  roleId: "",
  menuIds: [],
});

const updateDialogFormVisible = ref(false);

const createDialogFormVisible = ref(false);

const allocateDialogFormVisible = ref(false);

const curRow: any = ref({});

const pageRes = ref({
  totalPage: 0,
  total: 0,
});

const tableData: any = ref([]);

const menuList: any = ref([]);

function reqTableList() {
  RoleAPI.getRoleList(params.value).then((res) => {
    tableData.value = [];
    pageRes.value.totalPage = res.totalPage;
    pageRes.value.total = res.total;
    for (const v of res.list) {
      tableData.value.push(v);
    }
  });
}

function reqMenuList() {
  MenuAPI.getMenuList().then((res) => {
    console.log(res);
    menuList.value = [];
    for (const v of res) {
      const res1 = {
        label: v.title,
        value: v.id,
        children: [] as any,
      };
      for (const vv of v.children) {
        const temp = {
          label: vv.title,
          value: vv.id,
        };
        res1.children.push(temp);
      }
      menuList.value.push(res1);
    }
  });
}

function reqRoleList(roleId: number) {
  allocForm.menuIds = [];
  RoleAPI.getRoleMenuList(roleId).then((res) => {
    console.log(res);
    const result = [];
    for (const v of res) {
      if (v.parentId == 0) {
        continue;
      }
      result.push([v.parentId, v.id]);
    }
    allocForm.menuIds = result;
  });
}

function pageChange(v: any) {
  console.log(v);
  console.log();
  params.value.pageNum = v;
  reqTableList();
}

function pad(num: any) {
  return num.toString().padStart(2, "0");
}

function formatDateTime(date: any) {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  return `${year}-${pad(month)}-${pad(day)} ${pad(hour)}:${pad(minute)}:${pad(
    second
  )}`;
}

function verify(row: any) {
  curRow.value = Object.assign({}, row);
  console.log(curRow.value);
  updateDialogFormVisible.value = true;
}

function handleUpdate(row: any) {
  curRow.value = Object.assign({}, row);
  console.log(curRow.value);
  updateDialogFormVisible.value = true;
}

onMounted(() => {
  reqTableList();
});

function parentMenuChage(v: any) {
  console.log(v);
  form.parentId = v;
}

function confirmUpdate() {
  RoleAPI.updateRole(curRow.value).then((res) => {
    ElMessage({
      type: "success",
      message: "更新成功",
    });
    updateDialogFormVisible.value = false;
    reqTableList();
  });
}

function handleDelete(row: any) {
  ElMessageBox.confirm("确认删除?", "", {
    confirmButtonText: "OK",
    cancelButtonText: "取消",
    type: "确认",
  }).then(() => {
    RoleAPI.deleteRole(row.id).then((res) => {
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      reqTableList();
    });
  });
}

function createMenu() {
  form.name = "";
  form.description = "";
  createDialogFormVisible.value = true;
}

function confirmCreate() {
  if (form.name == "") {
    ElMessage({
      type: "warning",
      message: "请输入名称",
    });
    return;
  }
  if (form.name.length > 200) {
    ElMessage({
      type: "warning",
      message: "名称太长",
    });
    return;
  }
  if (form.description == "") {
    ElMessage({
      type: "warning",
      message: "请输入描述",
    });
    return;
  }
  if (form.description.length > 200) {
    ElMessage({
      type: "warning",
      message: "描述太长",
    });
    return;
  }
  RoleAPI.createRole(form).then((res) => {
    ElMessage({
      type: "success",
      message: "添加成功",
    });
    createDialogFormVisible.value = false;
    form.parentId = "";
    form.title = "";
    form.name = "";
    form.icon = "";
    form.path = "";
    form.component = "";
    reqTableList();
  });
}

function allocateMenu(row: any) {
  allocateDialogFormVisible.value = true;
  allocForm.roleId = row.id;
  reqMenuList();
  reqRoleList(allocForm.roleId);
}

function confirmAllocate() {
  console.log(allocForm);
  const newMenu: any[] = [];
  for (const v of allocForm.menuIds) {
    if (!newMenu.includes(v[0])) {
      newMenu.push(v[0]);
    }
    if (!newMenu.includes(v[1])) {
      newMenu.push(v[1]);
    }
  }
  console.log(newMenu);
  allocForm.menuIds = newMenu;
  RoleAPI.allocMenu(allocForm).then((res) => {
    allocForm.roleId = "";
    allocForm.menuIds = [];
    allocateDialogFormVisible.value = false;
    ElMessage({
      type: "success",
      message: "分配成功，一秒后刷新菜单",
    });
    setTimeout(() => {
      location.href = "/";
    }, 1000);
  });
}
</script>
